<?php

declare (strict_types=1);

namespace app\admin\middleware;

use app\admin\service\AdminTokenService;
use Closure;
use think\response\Json;
use tmcore\traits\JsonTrait;

/**
 * 登录中间件
 */
class LoginMiddleware
{
    use JsonTrait;

    /**
     * 登录验证
     * @param $request
     * @param Closure $next
     * @return mixed|Json
     */
    public function handle($request, Closure $next)
    {
        $token = $request->header('authorization');
        if (empty($token)) return self::error('请求参数缺少token', 10006);

        $adminInfo = AdminTokenService::getAdminInfo($token);
        if (empty($adminInfo)) {
            return self::error(AdminTokenService::getError('登录失败，请重新登录'), 100007);
        }

        // request赋值管理员信息
        $request->adminInfo = $adminInfo;
        $request->adminId = $adminInfo['id'] ?? 0;

        return $next($request);
    }

}